package com.chukun.disruptor.netty.client;

import com.chukun.disruptor.netty.codec.NettyMarshallingCodeCFactory;
import com.chukun.disruptor.netty.common.CommonConstants;
import com.chukun.disruptor.netty.handler.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;


public class NettyClient {

    public  NettyClient(){
        this.connect(CommonConstants.SERVER_HOST,CommonConstants.SERVER_PORT);
    }

    private void connect(String serverHost, int serverPort) {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        //创建客户端辅助类
        Bootstrap bootstrap = new Bootstrap();

        try{
            bootstrap.group(workGroup)
                    //初始化channel
                    .channel(NioSocketChannel.class)
                    //表示缓存区动态调配（自适应）
                    .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
                    //缓存区 池化操作
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            sc.pipeline().addLast(NettyMarshallingCodeCFactory.buildMarshallingDecoder());
                            sc.pipeline().addLast(NettyMarshallingCodeCFactory.buildMarshallingEncoder());
                            sc.pipeline().addLast(new ClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect(serverHost, serverPort).sync();
            System.err.println("client connection.....");
            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
           workGroup.shutdownGracefully();
        }
    }
}
